package cn.yan.luowowo.service.impl;


import cn.yan.luowowo.domain.StrategyCatalog;
import cn.yan.luowowo.query.StrategyCatalogQuery;
import cn.yan.luowowo.repository.StrategyCatalogRepository;
import cn.yan.luowowo.service.StrategyCatalogService;
import cn.yan.luowowo.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StrategyCatalogServiceImpl implements StrategyCatalogService{


    //注入StrategyCatalogRepository
    @Autowired
    private StrategyCatalogRepository strategyCatalogRepository;

    @Autowired
    private MongoTemplate template;


    @Override
    public StrategyCatalog get(String id) {
        return strategyCatalogRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyCatalog> list() {
        return strategyCatalogRepository.findAll();
    }

    @Override
    public void save(StrategyCatalog strategyCatalog) {
        strategyCatalog.setId(null);
        strategyCatalogRepository.save(strategyCatalog);

    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {

        strategyCatalogRepository.deleteById(id);
    }

    /*
    思路：因为template没有直接可以完成这个业务的方法，需要手动创建query对象封装条件
     */
    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQuery vo) {

        //创建query条件对象
        Query query = new Query();
        //调用模板的方法查询总记录数
        long count = template.count(query, StrategyCatalog.class);
        //如果总条数为0，则返回empty(空数据)
        if(count==0){
            return Page.empty();
        }
        //如果有数据，则页面显示数据集合list,(PageRequest.of,springboot的分页，参数1：开始页,
        //参数2：每页显示数据，参数3：升降序参数,参数4：根据什么字段升降序)
        /*
        Pageable ,Spring Data库中定义的一个接口，
        用于构造翻页查询，是所有分页相关信息的一个抽象，
        通过该接口，可以得到和分页相关所有信息（例如pageNumber、pageSize等），
        这样，Jpa就能够通过pageable参数来得到一个带分页信息的Sql语句。
         */
        Pageable pageable = PageRequest.of(vo.getCurrentPage()-1,
                vo.getPageSize(), Sort.Direction.DESC,"_id");
        //将pageable添加到query
        query.with(pageable);
        //根据这个query查询
        List<StrategyCatalog> list = template.find(query, StrategyCatalog.class);

        //最后拼接成page对象,返回对象（参数包括查询结果，pageable，count）---因为Page接口的普通实现类是PageImpl

        return new PageImpl<>(list,pageable,count);
    }

    @Override
    public void saveOrUpdate(StrategyCatalog strategyCatalog) {
        if(StringUtils.hasLength(strategyCatalog.getId())){
            //mongodb得更新是全量更新，所有操作是先查询再替换最后更新
            //这里没有查询是因为：修改的参数个数刚好跟数据库的列一样
            this.update(strategyCatalog);

        }else {
            //
            this.save(strategyCatalog);
        }

    }

    @Override
    public List<CatalogVO> groupList() {

        List<CatalogVO> list = new ArrayList<>();

        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,

                Aggregation.group("destName").

                        push("name").as("names").

                        push("id").as("ids")

        );

        AggregationResults<Map> result = template.aggregate(agg,Map.class);

        List<Map> datas = result.getMappedResults();

        for (Map data : datas) {

            CatalogVO vo = new CatalogVO();

            vo.setDestName(data.get("_id").toString());

            List<Map<String, Object>> mm = new ArrayList<>();

            List<Object> names = (List<Object>) data.get("names");

            List<Object> ids = (List<Object>) data.get("ids");

            for (int i = 0;i < names.size(); i++) {

                Map<String, Object> vv = new HashMap<>();

                String name = names.get(i).toString();

                String id = ids.get(i).toString();

                vv.put("id", id);

                vv.put("name", name);

                mm.add(vv);

            }

            vo.setMapList(mm);

            list.add(vo);

        }

        System.out.println(list);

        return list;
    }


}
